package com.ltu.service.impl;

import java.io.IOException;

import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.ltu.constant.CommonConstant;
import com.ltu.domain.mp_entity.VerifySmsCode;
import com.ltu.mapper.VerifySmsCodeMapper;
import com.ltu.model.request.smscode.GetSmsCodeReq;
import com.ltu.model.request.smscode.VerifySmsCodeReq;
import com.ltu.service.VerifySmsCodeService;
import com.ltu.util.common.StrUtils;
import com.ltu.util.datetime.DateUtils;
import com.ltu.util.redis.RedistUtil;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author vk@rongding123
 * @since 2020-08-25
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class VerifySmsCodeServiceImpl extends ServiceImpl<VerifySmsCodeMapper, VerifySmsCode> implements VerifySmsCodeService {
//	@Value("${qcloud.appid}")   
	private int appId=1400846392;
//	@Value("${qcloud.appkey}")
	private String appKey="175b6badb99024bac51e61af4a61ca8b";
    private final RedistUtil redistUtil;

    private final static String REDIS_KEY_SMSCODE_PREFIX = "REDIS_KEY_SMSCODE_PREFIX:";
    private final static Long REDIS_SMSCODE_DATA_TIMEOUT = Long.valueOf(CommonConstant.DEFAULT_SMS_EXPIRE_TIME);//默认30分钟
    private final static String regionId= "cn-wulanchabu",  accessKeyId= "",  secret="",SignName = "";
    

    /**
     * 获取短信验证码
     * @param req
     * @return
     */
    public boolean getSmsCode(GetSmsCodeReq req) {
        String smsStr = StrUtils.getRandomNumberStr(4);
        VerifySmsCode verifySmsCode = new VerifySmsCode();
        verifySmsCode.setPhone(req.getUserPhone())
            .setSmsCode(smsStr)
            .setExpireTime( CommonConstant.DEFAULT_SMS_EXPIRE_TIME+ DateUtils.currentSecs().intValue())
            .setRemark("验证码有效时间：" + CommonConstant.DEFAULT_SMS_EXPIRE_TIME + "s");
        
        //使用redis进行缓存
        redistUtil.setValue(REDIS_KEY_SMSCODE_PREFIX+req.getUserPhone(),
        		JSONObject.toJSONString(verifySmsCode),
                REDIS_SMSCODE_DATA_TIMEOUT);
        //send sms
        return sendTencentSms(req.getUserPhone(), smsStr);
//        return sendSmsAliyun(req.getUserPhone(), smsStr);
    }

    /**
     * 校对短信码
     * @param verifySmsCodeReq
     * @return
     */
    public boolean verifySmsCode(VerifySmsCodeReq verifySmsCodeReq) {
        //从redis获取
        String smsCodeStr = (String)redistUtil.getValue(REDIS_KEY_SMSCODE_PREFIX+verifySmsCodeReq.getUserPhone());
        if (smsCodeStr == null)
            return false;
        VerifySmsCode verifySmsCode = JSONObject.parseObject(smsCodeStr, VerifySmsCode.class);
        return verifySmsCode.getSmsCode().equals(verifySmsCodeReq.getSmsCode());
    }

    /**
     * 通过手机号获取校对码
     * @param phone
     * @return
     */
    public VerifySmsCode getVerifySmsCodeByPhone(String phone) {
        if (StrUtils.isTrimNull(phone))
            return null;
        QueryWrapper<VerifySmsCode> condition = new QueryWrapper<>();
        condition.eq("phone",phone);
        return super.getOne(condition);
    }

    public static boolean sendSmsAliyun(String phoneNum, String code) {
        DefaultProfile profile = DefaultProfile.getProfile(regionId ,accessKeyId,secret );
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("SignName", SignName);
        request.putQueryParameter("TemplateCode", "SMS_276467345");
        request.putQueryParameter("PhoneNumbers", phoneNum);
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return true;
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }

        return false;
    }
    public static boolean sendPayRentNotice(String phoneNum, String msg) {
    	DefaultProfile profile = DefaultProfile.getProfile(regionId ,accessKeyId,secret );
    	IAcsClient client = new DefaultAcsClient(profile);
    	
    	CommonRequest request = new CommonRequest();
    	request.setSysMethod(MethodType.POST);
    	request.setSysDomain("dysmsapi.aliyuncs.com");
    	request.setSysVersion("2017-05-25");
    	request.setSysAction("SendSms");
    	request.putQueryParameter("RegionId", regionId);
    	request.putQueryParameter("SignName", SignName);
    	request.putQueryParameter("TemplateCode", "SMS_461325394");
    	request.putQueryParameter("PhoneNumbers", phoneNum);
    	request.putQueryParameter("TemplateParam", msg);
    	try {
    		CommonResponse response = client.getCommonResponse(request);
    		System.out.println(response.getData());
    		return true;
    	} catch (ServerException e) {
    		e.printStackTrace();
    	} catch (ClientException e) {
    		e.printStackTrace();
    	}
    	
    	return false;
    }
    
    // 腾讯
    public boolean sendTencentSms(String phoneNum, String code) {
    	 try {
	            //短信模板中的参数列表
	            String[] params = {code};
	            SmsSingleSender sender = new SmsSingleSender(appId,appKey);
	            SmsSingleSenderResult result = sender.sendWithParam("86", phoneNum,
	            		1892605, params, "智晟体育", "", "");
	            System.out.println(com.alibaba.fastjson.JSONObject.toJSONString(result));
	            return true;
	        } catch (HTTPException e) {
	            // HTTP 响应码错误
	            e.printStackTrace();
	        } catch (JSONException e) {
	            // JSON 解析错误
	            e.printStackTrace();
	        } catch (IOException e) {
	            // 网络 IO 错误
	            e.printStackTrace();
	        } 
    	
    	return false;
    }
    

}
